package com.lagou.rpc.consumer.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class RpcClient {
        private RpcClientHandler handler = new RpcClientHandler();
        private ExecutorService executorService = Executors.newCachedThreadPool();
        private String ip;

    public RpcClient(String ip) {
        this.ip = ip;
    }

    public void  initClient() throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.SO_KEEPALIVE,true);
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,3000);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                ChannelPipeline pipeline = socketChannel.pipeline();
                pipeline.addLast(new StringDecoder());
                pipeline.addLast(new StringEncoder());
                pipeline.addLast(handler);

            }
        });
        ChannelFuture channelFuture = bootstrap.connect(ip, 9999).sync();
        Channel channel = channelFuture.channel();
    }

    public Object send( String msg) throws ExecutionException, InterruptedException {
        handler.setMsg(msg);
        Future<String> future = executorService.submit(handler);
        return  future.get();
    }
}
